package com.eva.cms.biz.resource;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eva.cms.biz.resource.vo.CmsResourceVO;
import com.eva.dao.cms.model.CmsResource;
import com.eva.dao.cms.model.CmsResourceGroup;
import com.eva.framework.cache.CacheProxy;
import com.eva.service.cms.CmsResourceGroupService;
import com.eva.service.cms.CmsResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CmsResourceBiz {

    @Resource
    private CmsResourceService cmsResourceService;

    @Resource
    private CmsResourceGroupService cmsResourceGroupService;

    @Resource
    private CacheProxy<String, List<CmsResourceVO>> cacheProxy;

    /**
     * 根据资源组唯一标识查询资源
     *
     * @param groupUid 资源组唯一标识
     * @return 分页数据
     */
    public List<CmsResourceVO> findListByGroupUid(String groupUid) {
        log.info("根据资源组唯一标识查询资源，请求参数: {}", groupUid);
        CmsResourceGroup dbCmsResourceGroup = cmsResourceGroupService.findByUid(groupUid);
        if (dbCmsResourceGroup == null) {
            return Collections.emptyList();
        }
        QueryWrapper<CmsResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(CmsResource::getTitle, CmsResource::getSubTitle,
                        CmsResource::getValue,
                        CmsResource::getValueType,
                        CmsResource::getConfig)
                .eq(CmsResource::getGroupId, dbCmsResourceGroup.getId())
                .eq(CmsResource::getDisabled, Boolean.FALSE)
                .eq(CmsResource::getDeleted, Boolean.FALSE)
                .orderByAsc(CmsResource::getSort)
        ;
        return BeanUtil.copyToList(cmsResourceService.findList(queryWrapper), CmsResourceVO.class);
    }

    /**
     * 根据资源组唯一标识集查询资源
     *
     * @param groupUids 资源组唯一标识集合
     * @return Map<String, List<CmsResourceVO>> Map<资源组唯一标识, List<资源>>
     */
    public Map<String, List<CmsResourceVO>> findListByGroupUids (List<String> groupUids) {
        if (CollectionUtils.isEmpty(groupUids)) {
            return Collections.emptyMap();
        }
        Map<String, List<CmsResourceVO>> result = new HashMap<>();
        for (String groupUid : groupUids) {
            String cacheKey = "resource:group:" + groupUid + ":resources";
            List<CmsResourceVO> resources = cacheProxy.get(cacheKey);
            if (resources != null) {
                result.put(groupUid, resources);
                continue;
            }
            resources = this.findListByGroupUid(groupUid);
            cacheProxy.put(cacheKey, resources);
            result.put(groupUid, resources);
        }
        return result;
    }
}
